package com.boolib.http.core.abstracts;

import com.boolib.http.core.defaults.DefaultReusableStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Locale;
import java.util.Optional;

/**
 * 构建一个可重复读、可替换数据的Stream流
 */
@Slf4j
public  abstract class AbstractHttpRequestReusableStreamWrapper extends HttpServletRequestWrapper {


    protected HttpServletRequest httpServletRequest;

    protected  byte[] decodeStreamData;

    protected String method;

    protected String contentType;

    protected String requestPath;


    public AbstractHttpRequestReusableStreamWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.fillRequestAttribute(request);
    }

    /**
     * 填充请求的属性
     * @param httpServletRequest
     * @throws IOException
     */
    private void fillRequestAttribute(HttpServletRequest httpServletRequest) throws IOException {

        HttpServletRequest request = this.httpServletRequest  = httpServletRequest;
        this.decodeStreamData = IOUtils.toByteArray(request.getInputStream());
        log.info("decodeStreamData:{}",new String(decodeStreamData));
        this.method = request.getMethod().toLowerCase(Locale.ROOT);
        this.contentType  = Optional.ofNullable(request.getContentType()).orElse("application/x-www-form-urlencoded").toLowerCase(Locale.ROOT);
        this.requestPath = request.getServletPath();

        if(log.isDebugEnabled()){
            log.debug("request method: {}",  this.method);
            log.debug("request contentType: {}",  this.contentType);
            log.debug("request requestPath: {}",  this.requestPath);
        }

    }


    @Override
    public ServletInputStream getInputStream() {
        byte[] bytes = this.decodeStreamData;
        return new DefaultReusableStream(bytes);
    }





    public void refreshData(byte[] bytes){
        this.decodeStreamData = bytes;
    }




}
